# coding=utf-8
from flask import Blueprint, request
from model import Voucher, SeckillVoucher
from utils import restful
from .common import VoucherHelper
from utils.ID_Creator import snow_id_creator
from setting import Prefixs
from form.voucher import SecKillVoucherForm
from decorator import login_required
bp = Blueprint("voucher", __name__, url_prefix='/voucher')
sets = set()
nums = 0


@bp.route("/list/<id>")
def queryVoucherOfShop(id):
    vouchers = Voucher.query.filter_by(shopID=id).all()
    voucher_list = []
    for voucher in vouchers:
        voucher = voucher.to_dict()
        if voucher.get("type") == 1:  # 代表是秒杀券，需要查询额外信息。
            seckillVoucher = SeckillVoucher.query.filter_by(voucherID=voucher.get('id')).first()
            voucher['stock'] = seckillVoucher.stock
            voucher["endTime"] = seckillVoucher.endTime
            voucher['beginTime'] = seckillVoucher.beginTime
        voucher_list.append(voucher)
    print(voucher_list)
    return restful.success(data=voucher_list)


@bp.route("/add_seckill_voucher", methods=["POST"])
@login_required
def addSeckillVoucher():
    form = SecKillVoucherForm(data=request.json)
    if not form.validate():
        print(form.errors)
        print(form.data)
        return restful.fail(), 404
    VoucherHelper.addSeckillVoucher(stock=form.stock.data, beginTime=form.beginTime.data,
                                    endTime=form.endTime.data, shopID=form.shopID.data, title=form.title.data,
                                    subTitle=form.subTitle.data, rules=form.rules.data,
                                    payValue=form.payValue.data, actualValue=form.actualValue.data,
                                    type=form.type.data, status=form.status.data)
    return restful.success(message="优惠券创建成功！")
# # 大约10000的计算量才会对flask的接口有影响，接口并发量大概能达到700以上
# @bp.route("/test")
# def voucher_test():
#     global nums, sets
#     id = snow_id_creator(voucher_create_profix)
#     nums += 1
#     sets.add(id)
#     num = 0
#     for i in range(100):
#         for j in range(10):
#             num += (i * 2)
#     print(id, nums, len(sets))
#     return str(id) + " " + str(nums) + " " + str(len(sets))
